package com.hectopascal.goalance.service;

import com.hectopascal.goalance.pojo.User;
import com.hectopascal.goalance.pojo.dto.UserAdd;
import com.hectopascal.goalance.pojo.dto.UserBack;
import com.hectopascal.goalance.repository.BUserRepository;
import com.hectopascal.goalance.repository.UserRepository;
import com.hectopascal.goalance.service.Ipml.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class UserService implements IUserService {
    @Autowired
    UserRepository userRepository;
    @Autowired
    BUserRepository bUserRepository;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Value("${file.upload-dir.photos}")
    private String uploadDirPhoto;
    @Override
    public User userAdd(UserAdd userAdd) {
        Optional<User> userOptional = userRepository.findByUsername(userAdd.getUsername());
        if (!userOptional.isEmpty()) {
            throw new IllegalArgumentException("用户名已存在");
        }
        if(userAdd.getPassword().length()<6||userAdd.getPassword().length()>12){
            throw new IllegalArgumentException("密码必须在6位到12位之间");
        }
        //如果role=3，弹出错误
        if(userAdd.getRole()==3){
            throw new IllegalArgumentException("权限不足");
        }
        User user = new User();
        // 1. 对密码进行加密
        String encodedPassword = passwordEncoder.encode(userAdd.getPassword());
        BeanUtils.copyProperties(userAdd, user);
        user.setPassword(encodedPassword);
        return userRepository.save(user);

    }

    //根据id查询用户
    @Override
    public UserBack getUser(Integer userId) {
        Optional<UserBack> userBack = bUserRepository.findUserById(userId);
        UserBack user = userBack.get();
        if (user.getRole().equals("manager")) {
            user.setRole("主管");
        } else if (user.getRole().equals("employee")) {
            user.setRole("员工");
        } else if (user.getRole().equals("admin")) {
            user.setRole("管理员");
        }
        return user;
    }

    //用户登录
    @Override
    public UserBack userLogin(User user) {
        Optional<UserBack> luser = bUserRepository.findByUsername(user.getUsername());
        if (luser.isEmpty()) {
            throw new IllegalArgumentException("用户名错误");
        }
        if (!passwordEncoder.matches(user.getPassword(),luser.get().getPassword() )) {
            throw new IllegalArgumentException("密码错误");
        }else{
            return luser.get();
        }
    }

    @Override
    public boolean verifyPassword(User user) {
        if(user.getPassword()==null){
            return true;
        }
        Optional<UserBack> Vuser = bUserRepository.findUserById(user.getId());
        if (Vuser.isEmpty()) {
            throw new IllegalArgumentException("用户为空");
        }
        if (!passwordEncoder.matches(user.getPassword(),Vuser.get().getPassword() )) {
            return false;
        }else{
            return true;
        }
    }

    @Override
    public int userUpdate(User user) {
        bUserRepository.findUserById(user.getId()).orElseThrow(()->{
            throw new IllegalArgumentException("用户不存在，参数异常");
        });
        String encodedPassword = null;
        if(user.getPassword()!=null){
            encodedPassword = passwordEncoder.encode(user.getPassword());
        }
        return userRepository.updateUser(user.getUsername(),encodedPassword,user.getRole(),user.getDepartmentId(),user.getId());
    }

    @Override
    public int userDelete(Integer userId) {
        bUserRepository.findUserById(userId).orElseThrow(()->{
            throw new IllegalArgumentException("用户不存在，参数异常");
        });
        return userRepository.deleteUserById(userId);
    }

    @Override
    public Map<String, Object> getUsersInfo(Integer page, Integer size, String role,Integer departmentId,String username) {
        Integer total = bUserRepository.findAllUsersPage(role,departmentId,username).get();
        Integer offset = ( page-1 )*size;
        Optional<List<UserBack>> userBack = bUserRepository.findAllUsers(offset,size,role,departmentId
                ,username);
        List<UserBack> userBacks=userBack.get();
        //设置List中的每个用户的role，string值为manager改为主管，employee改为员工，admin改为管理员
        for (UserBack userBack1 : userBacks) {
            if (userBack1.getRole().equals("manager")) {
                userBack1.setRole("主管");
            } else if (userBack1.getRole().equals("employee")) {
                userBack1.setRole("员工");
            } else if (userBack1.getRole().equals("admin")) {
                userBack1.setRole("管理员");
            }
        }
        //返回total和userBacks的Map对象
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("userBacks", userBacks);
        return result;
    }

    @Override
    public List<UserBack> getEmployeeInfo(Integer userId) {
        Integer departmentId = userRepository.getDepartmentId(userId);
        List<UserBack> userBack = userRepository.findByRoleAndDep("employee",departmentId);
        return userBack;
    }

    @Override
    public String userUpdateAvatar(MultipartFile file, Integer userId) throws IOException {
        bUserRepository.findUserById(userId).orElseThrow(()->{
            throw new IllegalArgumentException("用户不存在，参数异常");
        });
        String endName;
        if(file.getOriginalFilename().contains(".png")){
            endName=".png";
        }else{
            endName=".jpg";
        }
        String fileName= UUID.randomUUID().toString() + "_" + userId;
        String filePath= uploadDirPhoto + "/" + fileName + endName;
        File dest = new File(filePath);
        System.out.println(filePath);
        file.transferTo(dest.getAbsoluteFile());
        userRepository.updateAvatar(filePath,userId);
        return filePath;
    }
}
